package com.taobao.me.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taobao.base.model.RestResponse;
import com.taobao.base.model.TokenResponse;
import com.taobao.base.model.TokenUser;
import com.taobao.me.feignclient.AuthServiceClient;
import com.taobao.me.model.dto.AddressDto;
import com.taobao.me.model.dto.AddressPreview;
import com.taobao.me.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author erebus
 */
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("address")
public class AddressController {

    ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private AddressService addressService;
    @Autowired
    private AuthServiceClient authServiceClient;

    /**
     * 添加收货地址
     */
    @PostMapping("/insertAddress")
    public RestResponse<String> insertAddress(@RequestBody AddressDto addressDto, HttpServletRequest request) {
        TokenUser tokenUser = getTokenUser(request);

        return addressService.insertAddress(tokenUser.getUserId(), addressDto);
    }

    /**
     * 根据id获取收货地址
     */
    @GetMapping("/getAddress")
    public RestResponse<List<AddressDto>> getAddress(HttpServletRequest request) {
        TokenUser tokenUser = getTokenUser(request);


        RestResponse<List<AddressDto>> restResponse = addressService.getAddressById(tokenUser.getUserId());

        return restResponse;
    }

    /**
     * 删除收货地址
     */
    @DeleteMapping("/deleteAddress/{addressId}")
    public RestResponse<String> deleteAddress(@PathVariable("addressId") int addressId) {

        return addressService.deleteAddress(addressId);
    }

    /**
     * 修改地址
     */
    @PutMapping("/updateAddress")
    public RestResponse<String> updateAddress(@RequestBody AddressDto addressDto) {
        return addressService.updateAddress(addressDto);
    }

    /**
     * 获取预览地址
     */
    @GetMapping("/getAddressPreview")
    public RestResponse<List<AddressPreview>> getAddressPreview(HttpServletRequest request) {
        TokenUser tokenUser = getTokenUser(request);
        RestResponse<List<AddressPreview>> addressPreview = addressService.getAddressPreview(tokenUser.getUserId());
        return addressPreview;
    }


    /**
     * 解析token 获取用户信息
     */
    private TokenUser getTokenUser(HttpServletRequest request) {
        // 从请求头中获取 Authorization 字段
        TokenUser tokenUser = null;
        String authorizationHeader = request.getHeader("Authorization");
        // 检查是否包含 Bearer Token
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
            TokenResponse tokenResponse = authServiceClient.checkToken(token);
            String jsonString = tokenResponse.getUser_name();
            // 转TokeUser对象
            try {
                tokenUser = objectMapper.readValue(jsonString, TokenUser.class);
                System.out.println(tokenUser);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenUser;
    }
}
